<?php

App::uses('CompositeKeyModel', 'Model');

/**
 * OrganisationMemberContribution Model
 *
 * @property Member $Member
 * @property OrganisationMemberContribution $OrganisationContributionType
 */
class ModuleMemberContribution extends CompositeKeyModel {

    //The Associations below have been created with all possible keys, those that are not needed can be removed
    public $useDbConfig = "organisations";
    public $primaryKeys = array('id', 'organisation_id');
    
    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'ModuleContributionType' => array(
            'className' => 'ModuleContributionType',
            'foreignKey' => 'module_contribution_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'OrganisationMember' => array(
            'className' => 'OrganisationMember',
            'foreignKey' => 'organisation_member_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ModuleContributionReceipt' => array(
            'className' => 'ModuleContributionReceipt',
            'foreignKey' => 'module_contribution_receipt_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Currency' => array(
            'className' => 'Currency',
            'foreignKey' => 'currency_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ModuleContributionPaymentType' => array(
            'className' => 'ModuleContributionPaymentType',
            'foreignKey' => 'module_contribution_payment_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );


    public function getList($organisation_id = null,$receipt_dt = null ,$contribution_type_filter = 0){
        if($receipt_dt == null){
            $receipt_dt = date('Y-m-d');
        }

        $conditions = array(
            'ModuleMemberContribution.organisation_id' => $organisation_id,
            'ModuleContributionReceipt.receipt_dt' => $receipt_dt,
            'ModuleMemberContribution.active' => 1
        );

        if($contribution_type_filter != 0){
            $conditions['ModuleMemberContribution.module_contribution_type_id'] = $contribution_type_filter;
        }

        $data = $this->find('all', array(
            //'fields' => array('id', 'name', 'description'),
            'conditions' => $conditions,
            'contain'=>array(
                'ModuleContributionType'=>array('fields' => array('id', 'name')),
                'OrganisationMember'=>array(
                    'fields' => array('id', 'member_id','organisation_no'),
                    'Member'=>array('fields' => array('id', 'first_name','last_name')),
                ),
                'ModuleContributionReceipt'=>array('fields' => array('id', 'receipt_no','receipt_dt')),
                'ModuleContributionPaymentType'=>array('fields' => array('id', 'name')),
                'Currency'=>array('fields' => array('id', 'currency_code','currency_name')),
            )
        ));

        if ($data) {
            $list = array();

            foreach ($data as $d) {
                $list[] = array(
                    'receipt_dt'=>$d['ModuleContributionReceipt']['receipt_dt'],
                    'receipt_no'=>$d['ModuleContributionReceipt']['receipt_no'],
                    'organisation_no'=>$d['OrganisationMember']['organisation_no'],
                    'first_name'=>$d['OrganisationMember']['Member']['first_name'],
                    'last_name'=>$d['OrganisationMember']['Member']['last_name'],
                    'type'=>$d['ModuleContributionType']['name'],
                    'week'=>$d['ModuleMemberContribution']['week'],
                    'month'=>$d['ModuleMemberContribution']['month'],
                    'year'=>$d['ModuleMemberContribution']['year'],
                    'amount'=>$d['ModuleMemberContribution']['amount'],
                    'currency_code'=>isset($d['Currency']['currency_code']) ? $d['Currency']['currency_code']:'',
                    'currency_id'=>isset($d['Currency']['id']) ? $d['Currency']['id']:'',
                    'contribution_id'=>$d['ModuleMemberContribution']['id'],
                    'receipt_id'=>$d['ModuleContributionReceipt']['id'],
                    'payment_type_id'=>$d['ModuleContributionPaymentType']['id'],
                    'payment_type'=>$d['ModuleContributionPaymentType']['name'],
                    'cheque_no'=>$d['ModuleMemberContribution']['cheque_number'],
                    'cheque_status'=>$d['ModuleMemberContribution']['cheque_status']
                );
            }

            return array('status' => 'success', 'lists' => $list);
        }

        return array('status' => 'failed', 'message' => 'No contributions collection records.');
    }


    function getOverviewWeekly($organisation_id,$start_dt,$end_dt){

        $conditions = array(
            'ModuleMemberContribution.organisation_id' => $organisation_id,
            'ModuleMemberContribution.active' => 1,
            'ModuleContributionReceipt.receipt_dt >=' => $start_dt,
            'ModuleContributionReceipt.receipt_dt <=' => $end_dt
        );

        $export_data = $this->find('all', array(
            'fields'=>array('ModuleMemberContribution.id','ModuleMemberContribution.week','SUM(ModuleMemberContribution.amount) AS amount','ModuleMemberContribution.module_contribution_type_id'),
            'conditions' => $conditions,
            'contain'=>array(
                'ModuleContributionReceipt'=>array('fields'=>array('id')),
                'ModuleContributionType'=>array('fields'=>array('name'))
            ),
            'group'=>array('ModuleMemberContribution.week','ModuleMemberContribution.module_contribution_type_id'),
            'recursive' => 1
        ));

        $x_axis = array();
        $y_axis = array();
        $cty = ClassRegistry::init('ModuleContributionType')->find('all',array(
            'fields'=>array('ModuleContributionType.id','ModuleContributionType.name'),
            'conditions' => array(
                'ModuleContributionType.organisation_id' => $organisation_id,
                'ModuleContributionType.active' => 1
            ),
            'recursive' => -1
        ));
        foreach($cty as $key=>$value){
            $name = $value['ModuleContributionType']['name'];
            $y_axis[]=array(
                'name'=>$name,
                'data'=>array()
            );
        }

        for($x = 1; $x <= 5; $x++){ //Cycle through the 5 weeks
            $x_axis[]='Week '.$x;
            foreach($y_axis as $key_y=>$arr){
                $y_name = $arr['name'];
                $found = false;
                foreach($export_data as $key1=>$value){
                    $week = $value['ModuleMemberContribution']['week'];
                    $type = $value['ModuleContributionType']['name'];
                    if($week == $x && $type == $y_name ){
                        $found = true;
                        $amount = $value[0]['amount'];
                        $y_axis[$key_y]['data'][]=doubleval($amount);
                    }
                }
                if(!$found){ //Default to zero if no record found
                    $y_axis[$key_y]['data'][]=0;
                }
            }
        }


        return array(
            'x_axis'=>$x_axis,
            'y_axis'=>$y_axis
        );
    }


    function getOverviewMonth($organisation_id,$start_dt,$end_dt){

        $conditions = array(
            'ModuleMemberContribution.organisation_id' => $organisation_id,
            'ModuleMemberContribution.active' => 1,
            'ModuleContributionReceipt.receipt_dt >=' => $start_dt,
            'ModuleContributionReceipt.receipt_dt <=' => $end_dt
        );

        $export_data = $this->find('all', array(
            'fields'=>array('ModuleMemberContribution.id','ModuleMemberContribution.week','SUM(ModuleMemberContribution.amount) AS amount','ModuleMemberContribution.module_contribution_type_id'),
            'conditions' => $conditions,
            'contain'=>array(
                'ModuleContributionReceipt'=>array('fields'=>array('id')),
                'ModuleContributionType'=>array('fields'=>array('name'))
            ),
            'group'=>array('ModuleMemberContribution.module_contribution_type_id'),
            'recursive' => 1
        ));

        $pie_data = array();
        foreach($export_data as $key1=>$value){
            $amount = $value[0]['amount'];
            $type = $value['ModuleContributionType']['name'];
            $pie_data[] = array(
                $type,doubleval($amount)
            );
        }

        if ($pie_data) {
            $first_pie_data = $pie_data[0];
            $pie_data[0] = array(
                'name' => $first_pie_data[0],
                'y' => $first_pie_data[1],
                'sliced' => true,
                'selected' => true
            );
        }

        return array(
            'data'=>$pie_data
        );
    }


    function count_pagination($organisation_id,$receipt_dt,$receipt_no,$member_no,$contribution_type,$currency,$payment_type,$cheque_no = null,$cheque_status = null){

        $conditions = array('ModuleMemberContribution.organisation_id' => $organisation_id,'ModuleMemberContribution.active' => 1);
        if($receipt_dt != null){
            $conditions['ModuleContributionReceipt.receipt_dt'] = $receipt_dt;
        }
        if($receipt_no != null){
            $conditions['ModuleContributionReceipt.receipt_no'] = $receipt_no;
        }
        if($member_no != null){
            $conditions['ModuleMemberContribution.organisation_member_id'] = $member_no;
        }
        if($contribution_type != 0){
            $conditions['ModuleMemberContribution.module_contribution_type_id'] = $contribution_type;
        }
        if($currency != 0){
            $conditions['ModuleMemberContribution.currency_id'] = $currency;
        }
        if($payment_type != 0){
            $conditions['ModuleMemberContribution.module_contribution_payment_type_id'] = $payment_type;
        }
        if($cheque_no != null){
            $conditions['ModuleMemberContribution.cheque_number'] = $cheque_no;
        }
        if($cheque_status != null){
            $conditions['ModuleMemberContribution.cheque_status'] = $cheque_status;
        }

        $count = $this->find('count', array(
            'fields'=>array('ModuleMemberContribution.id'),
            'conditions' => $conditions,
            'contain'=>array(
                'ModuleContributionReceipt'=>array('fields'=>array('ModuleContributionReceipt.id')),
                'ModuleContributionPaymentType'=>array('fields' => array('ModuleContributionPaymentType.id')),
                'ModuleContributionType'=>array('fields'=>array('name'))
            ),
            'order' => array('ModuleContributionReceipt.receipt_dt' => 'desc'),
            'recursive' => 1
        ));

        return $count;
    }

    function load_pagination($organisation_id,$receipt_dt,$receipt_no,$member_no,$contribution_type,$currency,$payment_type,$offset = 0,$limit = 20,$cheque_no = null,$cheque_status = null){
        $conditions = array('ModuleMemberContribution.organisation_id' => $organisation_id,'ModuleMemberContribution.active' => 1);
        if($receipt_dt != null){
            $conditions['ModuleContributionReceipt.receipt_dt'] = $receipt_dt;
        }
        if($receipt_no != null){
            $conditions['ModuleContributionReceipt.receipt_no'] = $receipt_no;
        }
        if($member_no != null){
            $conditions['ModuleMemberContribution.organisation_member_id'] = $member_no;
        }
        if($contribution_type != 0){
            $conditions['ModuleMemberContribution.module_contribution_type_id'] = $contribution_type;
        }
        if($currency != 0){
            $conditions['ModuleMemberContribution.currency_id'] = $currency;
        }
        if($payment_type != 0){
            $conditions['ModuleMemberContribution.module_contribution_payment_type_id'] = $payment_type;
        }
        if($cheque_no != null){
            $conditions['ModuleMemberContribution.cheque_number'] = $cheque_no;
        }
        if($cheque_status != null){
            $conditions['ModuleMemberContribution.cheque_status'] = $cheque_status;
        }

        $data = $this->find('all', array(
            //'fields'=>array('ModuleMemberContribution.id'),
            'conditions' => $conditions,
            'contain'=>array(
                'ModuleContributionType'=>array('fields' => array('id', 'name')),
                'OrganisationMember'=>array(
                    'fields' => array('id', 'member_id','organisation_no'),
                    'Member'=>array('fields' => array('id', 'first_name','last_name')),
                ),
                'ModuleContributionReceipt'=>array('fields' => array('id', 'receipt_no','receipt_dt')),
                'ModuleContributionPaymentType'=>array('fields' => array('id', 'name')),
                'Currency'=>array('fields' => array('id', 'currency_code','currency_name')),
            ),
            'order' => array('ModuleContributionReceipt.created' => 'desc'),
            'limit' => $limit,
            'offset' => $offset
        ));

        $list = array();

        foreach ($data as $d) {
            $list[] = array(
                'receipt_dt'=>$d['ModuleContributionReceipt']['receipt_dt'],
                'receipt_no'=>$d['ModuleContributionReceipt']['receipt_no'],
                'organisation_no'=>$d['OrganisationMember']['organisation_no'],
                'organisation_member_id'=>$d['ModuleMemberContribution']['organisation_member_id'],
                'first_name'=>$d['OrganisationMember']['Member']['first_name'],
                'last_name'=>$d['OrganisationMember']['Member']['last_name'],
                'type'=>$d['ModuleContributionType']['name'],
                'week'=>$d['ModuleMemberContribution']['week'],
                'month'=>$d['ModuleMemberContribution']['month'],
                'year'=>$d['ModuleMemberContribution']['year'],
                'amount'=>$d['ModuleMemberContribution']['amount'],
                'currency_code'=>isset($d['Currency']['currency_code']) ? $d['Currency']['currency_code']:'',
                'currency_id'=>isset($d['Currency']['id']) ? $d['Currency']['id']:'',
                'contribution_id'=>$d['ModuleMemberContribution']['id'],
                'receipt_id'=>$d['ModuleContributionReceipt']['id'],
                'payment_type_id'=>$d['ModuleContributionPaymentType']['id'],
                'payment_type'=>$d['ModuleContributionPaymentType']['name'],
                'cheque_no'=>$d['ModuleMemberContribution']['cheque_number'],
                'cheque_status'=>$d['ModuleMemberContribution']['cheque_status']
            );
        }

        return $list;

    }


    function delete_contribution($organisation_id,$contribution_id){

        $data =  $this->updateAll(array('ModuleMemberContribution.active' => '0'), array('ModuleMemberContribution.id' => $contribution_id, 'ModuleMemberContribution.organisation_id' => $organisation_id));

        if($data){
            $response =  array('status' => 'success', 'message' => 'Contribution deleted successfully');
        }
        else{
            $response =  array('status' => 'failed', 'message' => 'Cannot delete contribution.');
        }

        return $response;
    }

    function cheques_status($organisation_id,$contribution_id,$cheque_status){

        $data =  $this->updateAll(array('ModuleMemberContribution.cheque_status' => "$cheque_status"), array('ModuleMemberContribution.id' => $contribution_id, 'ModuleMemberContribution.organisation_id' => $organisation_id));

        if($data){
            $response =  array('status' => 'success', 'message' => 'Cheque status changed successfully');
        }
        else{
            $response =  array('status' => 'failed', 'message' => 'Cannot change cheque status.');
        }

        return $response;
    }

}
